package com.ruoyi.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.minio.server.MinioService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.entity.VerInspiration;
import com.ruoyi.product.domain.ProductSku;
import com.ruoyi.service.VerInspirationItemService;
import com.ruoyi.service.VerInspirationService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/inspiration")
public class VerInspirationController extends BaseController {
    @Autowired
    private VerInspirationService verInspirationService;
    @Autowired
    private MinioService minioService;
    @Autowired
    private VerInspirationItemService verInspirationItemService;

    // 删除指定的灵感关联SKU
    @DeleteMapping("/{inspirationId}/skus")
    public AjaxResult deleteSpecificInspirationSkus(@PathVariable Long inspirationId,
                                                    @RequestBody List<Long> skuIds) {
        try {
            // 获取当前关联的SKU列表
            List<ProductSku> currentSkus = verInspirationItemService.getRelatedSkusByInspirationId(inspirationId);
            List<Long> currentSkuIds = currentSkus.stream()
                    .map(ProductSku::getId)
                    .collect(Collectors.toList());

            // 从当前列表中移除指定的SKU ID
            currentSkuIds.removeAll(skuIds);

            // 保存更新后的关联关系
            verInspirationItemService.saveInspirationSkuRelation(inspirationId, currentSkuIds);
            return success("取消关联商品成功");
        } catch (Exception e) {
            log.error("取消关联指定商品失败", e);
            return error("取消关联指定商品失败: " + e.getMessage());
        }
    }

    // 保存灵感关联的SKU
    @PostMapping("/{inspirationId}/skus")
    public AjaxResult saveInspirationSkus(@PathVariable Long inspirationId,
                                          @RequestBody List<Long> skuIds) {
        try {
            verInspirationItemService.saveInspirationSkuRelation(inspirationId, skuIds);
            return success("关联商品成功");
        } catch (RuntimeException e) {
            log.error("关联商品失败: {}", e.getMessage());
            return error(e.getMessage());
        } catch (Exception e) {
            log.error("关联商品失败", e);
            return error("保存失败: " + e.getMessage());
        }
    }

    // 获取灵感关联的SKU列表
    @GetMapping("/{inspirationId}/skus")
    public AjaxResult getInspirationSkus(@PathVariable Long inspirationId) {
        try {
            List<ProductSku> skus = verInspirationItemService.getRelatedSkusByInspirationId(inspirationId);
            return success(skus);
        } catch (Exception e) {
            log.error("获取灵感关联SKU列表失败", e);
            return error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取详细信息
     */
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        VerInspiration inspiration = verInspirationService.selectVerInspirationById(id);
        if (inspiration != null) {
            List<ProductSku> relatedSkus = verInspirationItemService.getRelatedSkusByInspirationId(id);
            inspiration.setRelatedSkus(relatedSkus);
        }
        return success(inspiration);
    }

    /**
     * 查询列表
     */
//    @PreAuthorize("@ss.hasPermi('system:inspiration:list')")
    @GetMapping("/list")
    public TableDataInfo list(VerInspiration verInspiration)
    {
        startPage();
        List<VerInspiration> list = verInspirationService.selectVerInspirationList(verInspiration);
        return getDataTable(list);
    }

    /**
     * 新增灵感
     */
    @Log(title = "新增灵感", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public AjaxResult add(@RequestPart("inspiration") String inspirationJson,
                          @RequestPart(value = "image", required = false) MultipartFile image) {
        try {
            // 手动将 JSON 字符串转换为 VerInspiration 对象
            ObjectMapper objectMapper = new ObjectMapper();
            VerInspiration verInspiration = objectMapper.readValue(inspirationJson, VerInspiration.class);

            if (image != null && !image.isEmpty()) {
                try {
                    // 生成文件名
                    String originalFileName = image.getOriginalFilename();
                    String fileExtension = "";
                    if (originalFileName != null && originalFileName.contains(".")) {
                        fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
                    }
                    String fileName = "inspiration_" + System.currentTimeMillis() + fileExtension;

                    // 上传文件到MinIO
                    Map<String, String> uploadResult = minioService.uploadFile(image, fileName);

                    // 根据ProductActivityController的实现处理返回结果
                    if (uploadResult != null && "true".equals(uploadResult.get("success"))) {
                        String imageUrl = uploadResult.get("fileUrl");
                        // 设置图片 URL 到 VerInspiration 实体中
                        verInspiration.setUrl(imageUrl);
                        log.info("设置图片URL: {}", imageUrl);
                    } else {
                        log.error("文件上传失败，返回结果: {}", uploadResult);
                        return error("文件上传失败");
                    }
                } catch (Exception e) {
                    log.error("图片上传失败", e);
                    return error("图片上传失败: " + e.getMessage());
                }
            }
            return toAjax(verInspirationService.insertVerInspiration(verInspiration));
        } catch (Exception e) {
            log.error("解析灵感数据失败", e);
            return error("数据解析失败: " + e.getMessage());
        }
    }

    /**
     * 修改灵感
     */
    @Log(title = "修改灵感", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/edit", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public AjaxResult edit(@RequestPart("inspiration") String inspirationJson,
                           @RequestPart(value = "image", required = false) MultipartFile image) {
        try {
            // 手动将 JSON 字符串转换为 VerInspiration 对象
            ObjectMapper objectMapper = new ObjectMapper();
            VerInspiration verInspiration = objectMapper.readValue(inspirationJson, VerInspiration.class);

            // 处理图片上传或清空逻辑
            if (image != null && !image.isEmpty()) {
                // 上传新图片的逻辑（保持不变）
                try {
                    String originalFileName = image.getOriginalFilename();
                    String fileExtension = "";
                    if (originalFileName != null && originalFileName.contains(".")) {
                        fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
                    }
                    String fileName = "inspiration_" + System.currentTimeMillis() + fileExtension;

                    Map<String, String> uploadResult = minioService.uploadFile(image, fileName);

                    if (uploadResult != null && "true".equals(uploadResult.get("success"))) {
                        String imageUrl = uploadResult.get("fileUrl");
                        verInspiration.setUrl(imageUrl);
                        log.info("设置新的图片URL: {}", imageUrl);
                    } else {
                        log.error("文件上传失败，返回结果: {}", uploadResult);
                        return error("文件上传失败");
                    }
                } catch (Exception e) {
                    log.error("图片上传失败", e);
                    return error("图片上传失败: " + e.getMessage());
                }
            }
            // 如果没有上传新图片，保留原有图片URL，不需要特别处理

            return toAjax(verInspirationService.updateVerInspiration(verInspiration));
        } catch (Exception e) {
            log.error("更新灵感数据失败", e);
            return error("数据更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除
     */
//    @PreAuthorize("@ss.hasPermi('system:inspiration:remove')")
    @Log(title = "删除灵感", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(verInspirationService.deleteVerInspirationByIds(ids));
    }
}
